/*
 * @Author: hulu20 - 563293401@qq.com
 * @Date: 2023-02-11 14:53:47
 * @Last Modified by: hulu20 - 563293401@qq.com
 * @Last Modified time: 2023-02-12 16:20:47
 * @Desc: 实现与数据库交互业务的封装
 */

package logic

import (
	"context"
	"fmt"
	"tasktor/internal/dao"
	"tasktor/internal/model"
	"tasktor/library/liberr"

	"github.com/gogf/gf/v2/frame/g"
)

var MetricsLogic = metricsLogic{} // 对外提供方法，变量大写

type metricsLogic struct{}

// 变量名大写，否则暴露不了func
func (s *metricsLogic) GetMonitorData(ctx context.Context, time int64) (res []*model.TaskMonitorInfo, err error) {
	//res = new(model.TaskMonitorInfo)
	err = g.Try(ctx, func(ctx context.Context) {
		//model := dao.TableMabangStockSkuSalesMonitor.Ctx(ctx) // 注意生成dao模型的时候，添加分组，否则会执行default库调用
		model := g.DB(dao.TableMabangStockSkuSalesMonitor.Group()).Model(dao.TableMabangStockSkuSalesMonitor.Table(), "a").Ctx(ctx) // 由于要使用别名连表，使用g.db模式
		// 连表获取数据
		model = model.RightJoin(fmt.Sprintf("SELECT max(id) as id from %s WHERE start_at >= %d GROUP BY task_type", dao.TableMabangStockSkuSalesMonitor.Table(), time), "b", "a.id = b.id")

		// 获取数据
		err = model.Scan(&res)
		liberr.ErrIsNil(ctx, err, "获取数据失败")
	})
	return
}
